package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.ClienteSaldo;
import ar.republicagroup.gestion.entities.Liquidacion;
import ar.republicagroup.gestion.services.ClienteSaldoServices;
import ar.republicagroup.gestion.services.LiquidacionServices;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.Validar;
import ar.republicagroup.gestion.util.helpers.Formato;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.awt.Color;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;

public class modalPanelAddPago extends javax.swing.JDialog {
    /* Log */
    Logger log = Logger.getLogger(modalPanelAddPago.class);
    /* Services */
    LiquidacionServices liquidacionServices = (LiquidacionServices)SpringUtils.getBean("liquidacionServices");
    ClienteSaldoServices clienteSaldoServices       = (ClienteSaldoServices)SpringUtils.getBean("clienteSaldoServices");
    /* Beans */
    private Liquidacion  liquidacion;
    private ClienteSaldo clienteSaldo;
    
    private boolean liquidPaid;
    private boolean isOpenFromAnotherParent;
   
    
    
    public modalPanelAddPago(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    public Liquidacion getLiquidacion() {
        return liquidacion;
    }

    public void setLiquidacion(Liquidacion liquidacion) {
        this.liquidacion = liquidacion;
    }

    public ClienteSaldo getClienteSaldo() {
        return clienteSaldo;
    }

    public void setClienteSaldo(ClienteSaldo clienteSaldo) {
        this.clienteSaldo = clienteSaldo;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtLiquidacion = new javax.swing.JTextField();
        txtCliente = new javax.swing.JTextField();
        txtRegistradoPor = new javax.swing.JTextField();
        txtTotal = new javax.swing.JTextField();
        txtTotalAPagar = new javax.swing.JTextField();
        txtDifLiquidAnterior = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        btnRegistrar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        lblMensajeSaldo = new javax.swing.JLabel();
        txtLiquidDif = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("...: Registrar pago :...");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setText("# Liquidación ");

        jLabel2.setText("Cliente");

        jLabel3.setText("Total Liquid");

        jLabel4.setText("Registrado por");

        jLabel5.setText("Total a pagar");

        txtLiquidacion.setEditable(false);

        txtCliente.setEditable(false);

        txtRegistradoPor.setEditable(false);

        txtTotal.setEditable(false);

        txtTotalAPagar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtTotalAPagarKeyPressed(evt);
            }
        });

        txtDifLiquidAnterior.setEditable(false);

        jLabel6.setText("Dif.Liquid ant");

        btnRegistrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/add.png"))); // NOI18N
        btnRegistrar.setText("Registrar");
        btnRegistrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRegistrarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        lblMensajeSaldo.setText("jLabel7");

        txtLiquidDif.setEditable(false);

        jLabel7.setText("Liquid + Dif");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5)
                            .addComponent(jLabel2)
                            .addComponent(jLabel7))
                        .addGap(23, 23, 23)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtTotalAPagar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(btnRegistrar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btnCancelar))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(txtLiquidDif, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtTotal, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtLiquidacion, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtCliente, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(txtRegistradoPor, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addGap(26, 26, 26)
                        .addComponent(txtDifLiquidAnterior, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(lblMensajeSaldo)))
                .addContainerGap(43, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtLiquidacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtRegistradoPor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDifLiquidAnterior, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(lblMensajeSaldo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtLiquidDif, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtTotalAPagar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnRegistrar)
                    .addComponent(btnCancelar))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrarActionPerformed
      if(esValidoElFormulario()){
          int opcion = JOptionPane.showConfirmDialog(this, UIMessages.getQuestionMessage("confirm_payment_total") + " : "+ Formato.decimalComaMilesConSigno(Double.parseDouble(txtTotalAPagar.getText())) + "\n" + UIMessages.getQuestionMessage("confirm_payment_liquidacion") ,UIMessages.getQuestionMessage("defaultQuestionTitle"), JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE);
               if(opcion == 0){
                    registrarPago();
                 }
           }
    }//GEN-LAST:event_btnRegistrarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        mostrarDatos();    
    }//GEN-LAST:event_formWindowOpened

    private void txtTotalAPagarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTotalAPagarKeyPressed
       if(evt.getKeyCode() == KeyEvent.VK_ENTER){
           if(esValidoElFormulario()){
               int opcion = JOptionPane.showConfirmDialog(this, UIMessages.getQuestionMessage("confirm_payment_total") + " : "+ Formato.decimalComaMilesConSigno(Double.parseDouble(txtTotalAPagar.getText())) + "\n" + UIMessages.getQuestionMessage("confirm_payment_liquidacion") ,UIMessages.getQuestionMessage("defaultQuestionTitle"), JOptionPane.YES_OPTION,JOptionPane.QUESTION_MESSAGE);
               if(opcion == 0){
                    registrarPago();
                 }
           }
       }
    }//GEN-LAST:event_txtTotalAPagarKeyPressed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        if(isOpenFromAnotherParent){
            int respuesta = JOptionPane.showConfirmDialog(this, UIMessages.getQuestionMessage("confirm_payment_cancel"), UIMessages.getQuestionMessage("defaultQuestionTitle"), JOptionPane.YES_NO_OPTION);
                if(respuesta == JOptionPane.YES_OPTION){
                    dispose();
                }else{
                    txtTotalAPagar.requestFocus();
                    txtTotalAPagar.selectAll();
                }
        }else{
            dispose();
        }
    }//GEN-LAST:event_btnCancelarActionPerformed

    
    private void registrarPago(){
            
            /* Registramos el importe pagado de la liquidación*/
            liquidacion.setImportePagado(Double.parseDouble(txtTotalAPagar.getText()));
            String mensajeLiquidacion = liquidacionServices.update(liquidacion);
            /*Actualizamos el saldo del cliente*/
            
            double saldoAnterior = clienteSaldo.getSaldoAnterior();
            clienteSaldo.setSaldoAnterior(clienteSaldo.getSaldoActual());
            clienteSaldo.setSaldoActual((Double.parseDouble(txtTotalAPagar.getText()) - clienteSaldo.getSaldoActual()));    
            
            
            String mensajeClienteSaldo = clienteSaldoServices.insert(clienteSaldo);
            
            if(mensajeLiquidacion != null && mensajeClienteSaldo != null){
                JOptionPane.showMessageDialog(this, mensajeClienteSaldo, UIMessages.getInfoMessage("onCompleteInsert_title"), JOptionPane.INFORMATION_MESSAGE);
                liquidPaid = true;
            }else {
                JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("onInsertError"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
            }
            
            
            if(!isOpenFromAnotherParent){
                frmReporteLiquidacion.btnBuscar.doClick();
            }
            
            dispose();
   }

    private void mostrarDatos(){
            txtLiquidacion.setText(String.valueOf(liquidacion.getId()));
            txtDifLiquidAnterior.setText(Formato.decimalComaMilesConSigno(liquidacion.getSaldoCliente()));
            txtCliente.setText(liquidacion.getClienteId().getNombre());
            txtRegistradoPor.setText(liquidacion.getUsuarioId().getNombre());
            txtTotal.setText(Formato.decimalComaMilesConSigno(liquidacion.getTotalLiquidacion()));
            
            if( liquidacion.getTotalLiquidacion() > 0 ){ 
                txtLiquidDif.setText(Formato.decimalComaMilesConSigno(liquidacion.getTotalLiquidacion() + (liquidacion.getSaldoCliente()*(-1))));
            } else {
                txtLiquidDif.setText(Formato.decimalComaMilesConSigno(liquidacion.getTotalLiquidacion() + (liquidacion.getSaldoCliente())));
            }
            
            txtTotalAPagar.requestFocus();
            
            if(liquidacion.getSaldoCliente() > 0){
                lblMensajeSaldo.setText("Cliente debe a RGroup");
                txtDifLiquidAnterior.setForeground(Color.BLUE);
            } else if(liquidacion.getSaldoCliente() < 0) {
                lblMensajeSaldo.setText("A favor del cliente");
                txtDifLiquidAnterior.setForeground(Color.RED);
            } else {
                lblMensajeSaldo.setVisible(false);
            }
            
    }
    
    private boolean esValidoElFormulario(){
        
        if(Validar.esVacio(txtTotalAPagar.getText()) || Validar.validarVacio(txtTotalAPagar.getText())){
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredInputPago"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
            txtTotalAPagar.requestFocus();
            return false;
        }
 
        if(!Validar.esUnDatoDouble(txtTotalAPagar.getText())){
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("decimal"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
            txtTotalAPagar.requestFocus();
            txtTotalAPagar.selectAll();
            return false;
        } 
        
        if(! Validar.esPositivo(Double.parseDouble(txtTotalAPagar.getText()))){
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("negativeValue"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
            txtTotalAPagar.requestFocus();
            txtTotalAPagar.selectAll();
            return false;
        }
        
        return true;
    }
    
    public boolean isLiquidPaid() {
        return liquidPaid;
    }

    
    public void setLiquidPaid(boolean isLiquidPaid) {
        this.liquidPaid = isLiquidPaid;
    }
    
    
    public boolean isIsOpenFromAnotherParent() {
        return isOpenFromAnotherParent;
    }

    
    public void setIsOpenFromAnotherParent(boolean isOpenFromAnotherParent) {
        this.isOpenFromAnotherParent = isOpenFromAnotherParent;
    }
    
    
    
    
   public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                modalPanelAddPago dialog = new modalPanelAddPago(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnRegistrar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblMensajeSaldo;
    private javax.swing.JTextField txtCliente;
    private javax.swing.JTextField txtDifLiquidAnterior;
    private javax.swing.JTextField txtLiquidDif;
    private javax.swing.JTextField txtLiquidacion;
    private javax.swing.JTextField txtRegistradoPor;
    private javax.swing.JTextField txtTotal;
    private javax.swing.JTextField txtTotalAPagar;
    // End of variables declaration//GEN-END:variables

   

}
